<?php
class Tv_Arte_Helpers_View_JQuery_Ajax extends Zend_View_Helper_Abstract
{
    
    const TYPE_POST     = 'POST';
    const TYPE_GET      = 'GET';
    
    private $_type = null;
    private $_success = null;
    private $_complete = null;
    private $_data = null;
    private $_url = null;
    
    /**
     * View Helper getter
     * 
     * @return Tv_Arte_Helpers_View_JQuery_Ajax 
     */
    public function JQuery_Ajax()
    {
        return $this;
    }
    
    public function reset()
    {
        $this->_type = null;
        $this->_success = null;
        $this->_complete = null;
        $this->_data = null;
        $this->_url = null;
        return $this;
    }
    
    public function __toString() {
        $js = "";
        $jsLitteral = Array();
        $js = "\$.ajax('" . $this->_url . "', ";
        if (!is_null($this->_success)) { 
            $jsLitteral[] = "success:" . $this->_success; 
        }
        if (!is_null($this->_complete)) { 
            $jsLitteral[] = "complete:" . $this->_complete; 
        }
        if (!is_null($this->_data)) { 
            $jsLitteral[] = "data:" . $this->_data; 
        }
        $js .= $this->_getLiteral($jsLitteral) . ");";
        return $js;
    }
    
    public function url($url)
    {
        $this->_url = $url;
        return $this;
    }
    
    public function complete($function)
    {
        $this->_complete = $function;
        return $this;
    }
    
    public function success($function)
    {
        $this->_success = $function;
        return $this;
    }
    
    public function data($data)
    {
        $this->_data = $data;
        return $this;
    }
    
    public function type($type)
    {
        $this->_type = (in_array($type, Array(self::TYPE_GET, self::TYPE_POST), true)) ? $type : self::TYPE_POST;
        return $this;
    }
    
    private function _getLiteral(Array $data)
    {
        $javascriptLiteral = "{";
        $lastKey = array_pop(array_keys($data));
        foreach ($data as $k => $v) {
            $javascriptLiteral .= $v . ((strcmp($lastKey, $k) !== 0) ? ", " : "");
        }
        $javascriptLiteral .= "}";
        return $javascriptLiteral;
    }
     
}